import React from 'react';
import { Col, Row, notification, message } from 'antd';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';
import Helmet from 'react-helmet'
import NewsDetail from '../store/news_detail'
import User from '../store/user_store'

// 引入公共组件
import PCHeader from './pc_header';
import PCFooter from './pc_footer';
import PCNewsImgModule from './pc_news_imgmodule';
import CommComments from './comm_comments';

import { post } from '../util/comm';
import { collectionUrl } from '../util/constant';

@inject((stores) => {
  const store = {
    newsDetail: stores.newsDetail,
    userStore: stores.userStore,
  }
  return store
})
@observer
class PCNewsDetail extends React.Component {
  constructor() {
    super();
    this.state = {
      news: '',
      newsName: '',
      isLoading: false,
    }
    this.collect = this.collect.bind(this);
    this.goComment = this.goComment.bind(this);
  }
  componentDidMount() {
    this.getNewsDetail();
  }
  // 更新完成
  componentDidUpdate(prevProps) {
    // 判断两次的url是否一致
    const oldPath = prevProps.location.pathname;
    const newPath = this.props.location.pathname;
    if (oldPath !== newPath) {
      this.getNewsDetail();
    }
  }
  // 获取新闻详情
  getNewsDetail() {
    this.props.newsDetail
      .getDetailNews(this.props.match.params.newsId).catch(e => message.error(`出错了${e}`))
  }
  // 获取元素的左上角的坐标
  getAbsPoint(e) {
    let x = 0;
    let y = 0;
    while (e) {
      x += e.offsetLeft;
      y += e.offsetTop;
      e = e.offsetParent
    }
    return { x, y };
  }
  // 跳转到评论
  goComment() {
    try {
      const commentArea = document.getElementById('comments-form');
      const top = this.getAbsPoint(commentArea).y;
      document.body.scrollTop = top;
    } catch (e) {
    }
  }
  // 添加收藏功能函数
  collect() {
    const param = {
      newsId: this.props.match.params.newsId,
      userId: this.props.userStore.userInfo.id,
    };
    if (!param.userId) {
      notification.error({
        message: '小白新闻提醒',
        description: '请先登录',
      })
      return;
    }
    // 用户已登录并且文章存在才能评论
    if (param.newsId && param.userId) {
      post(collectionUrl, param).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 1) {
            notification.success({
              message: '小白新闻提醒',
              description: '收藏该文章成功',
            })
          } else if (res.data.code === 10) {
            this.props.userStore.clearUserInfo();
            notification.error({
              message: '小白新闻提醒',
              description: '请登陆后再进行收藏',
            })
          } else {
            message.error(res.data.message);
          }
        } else {
          message.error(res.data.message);
        }
      })
    }
  }
  // dangerouslySetInnerHTML处理函数
  filter(data) {
    return {
      __html: data,
    }
  }
  asyncBootstrap() {
    return new Promise((resolve) => {
      this.props.newsDetail
        .getDetailNews(this.props.match.params.newsId)
        .then(() => resolve(true))
    })
  }
  render() {
    const id = this.props.match.params.newsId;
    const news =
      this.props.newsDetail.newsDetailData.get(id)
        ? this.props.newsDetail.newsDetailData.get(id).data : {}
    const { isLoading } = this.props.newsDetail
    return (
      <div id="pc">
        <div className="news-detail">
          <PCHeader newsName={news.channel} />
          <Helmet>
            <title>{news.title}</title>
          </Helmet>
          { !isLoading ?
            <Row>
              <Col span={18}>
                <h1 className="title">{news.title}</h1>
                <div className="handle-article">
                  <span className="collect" onClick={this.collect}>
                    +收藏该文章
                  </span>
                  <span className="gocomment" onClick={this.goComment} ref="gocomment">
                    +去评论
                  </span>
                  <span className="src">
                    来源:{news.src}
                  </span>
                  <span className="time">
                    时间:{news.time}
                  </span>
                </div>
                <div className="news-detail-content" dangerouslySetInnerHTML={this.filter(news.content)} />
                <CommComments newsId={-(0 - this.props.match.params.newsId)} pageSize={15} />
              </Col>
              <Col span={6}>
                <PCNewsImgModule type="头条" count="18" title="新闻头条" rowCount="2" />
              </Col>
            </Row>
              :
            <div className="loading">加载中...</div>
          }
          <PCFooter />
        </div>
      </div>
    )
  }
}
export default PCNewsDetail;

PCNewsDetail.propTypes = {
  match: PropTypes.objectOf(Object),
  location: PropTypes.objectOf(String),
  // newsList: PropTypes.instanceOf(NewsList),
  newsDetail: PropTypes.instanceOf(NewsDetail),
  userStore: PropTypes.instanceOf(User),
}
